package com.hlk.user.controller;

import com.hlk.user.PassportControllerApi;
import com.hlk.enums.ResponseStatusEnum;
import com.hlk.enums.UserStatusEnum;
import com.hlk.pojo.AppUser;
import com.hlk.pojo.bo.RegistLoginBO;
import com.hlk.result.Result;
import com.hlk.user.service.UserService;
import com.hlk.utils.*;
import com.hlk.utils.redis.RedisKeys;
import com.hlk.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-17 9:55
 */
@Slf4j
@RestController
public class PassportController implements PassportControllerApi {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private CookieUtils cookieUtils;

    @Override
    public Result getSMSCode(String mobile, HttpServletRequest request) {
        // 获取用户IP
        String userIP = IPUtil.getRequestIp(request);
        // 将IP存入redis中（如果存在key则不添加，如果不存在则添加）
        redisUtils.setnx60s(RedisKeys.getSmsCodeByIpKey(userIP), userIP);

        // 发送短信
        String code = (int) (Math.random() * 9 * 100000) + "";
//        smsUtils.sendSms(mobile, code);

        // 将验证码存入redis中
        redisUtils.set(RedisKeys.getSmsCodeByMobileKey(mobile), code, 5 * 60);
        Result.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        return Result.ok();
    }

    @Override
    public Result doLogin(RegistLoginBO registLoginBO, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
        // 校验参数是否符合
        if (result.hasErrors()) {
            Map<String, String> map = ValidateUtils.checkParams(result);
            return Result.errorMap(map);
        }

        String mobile = registLoginBO.getMobile();
        String smsCode = registLoginBO.getSmsCode();

        // 校验验证码是否匹配
        String redisSmsCode = redisUtils.get(RedisKeys.getSmsCodeByMobileKey(mobile));
        if (!redisSmsCode.equals(smsCode)) {
            return Result.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        // 判断是否有注册用户
        AppUser user = userService.selectUserByMobile(mobile);
        if (user != null && user.getActiveStatus().equals(UserStatusEnum.FROZEN.type)) {
            return Result.errorCustom(ResponseStatusEnum.USER_FROZEN);
        } else if (user == null) {
            user = userService.createUser(mobile);
        }

        // 保存用户分布式会话的相关操作
        Integer activeStatus = user.getActiveStatus();
        if (!activeStatus.equals(UserStatusEnum.FROZEN.type)) {
            String utoken = UUID.randomUUID().toString();
            // 保存token到redis
            redisUtils.set(RedisKeys.getUserTokenKey(user.getId()), utoken);
            // 保存用户信息到redis
            redisUtils.set(RedisKeys.getUserInfoKey(user.getId()), JsonUtils.objectToJson(user));

            // 保存用户id和token到cookie中
            cookieUtils.setCookie(response, "utoken", utoken, CookieUtils.COOKIE_MONTH);
            cookieUtils.setCookie(response, "uid", user.getId(), CookieUtils.COOKIE_MONTH);
        }

        // 登录成功后，需要删除短信验证码
//        redisUtils.del(RedisKeys.getSmsCodeByMobile(mobile));

        return Result.ok(user.getActiveStatus());
    }

    @Override
    public Result logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        redisUtils.del(RedisKeys.getUserTokenKey(userId));

        cookieUtils.setCookie(response, "utoken", "", CookieUtils.COOKIE_DELETE);
        cookieUtils.setCookie(response, "uid", "", CookieUtils.COOKIE_DELETE);

        return Result.ok();
    }
}
